﻿using System;
using System.Net;
using System.ServiceModel.Channels;
using System.IO;
using System.ServiceModel;

namespace SilverlightRestServices.Channels
{
    internal class RestMessageEncoder : MessageEncoder
    {
        public MessageVersion m_MessageVersion;

        public override String ContentType
        {
            get { return "application/unknown"; }
        }

        public override String MediaType
        {
            get { return "application"; }
        }

        public override MessageVersion MessageVersion
        {
            get { return this.m_MessageVersion; }
        }

        public RestMessageEncoder(MessageVersion messageVersion)
        {
            this.m_MessageVersion = messageVersion;
        }

        public override Boolean IsContentTypeSupported(String contentType)
        {
            return true;
        }

        public override Message ReadMessage(ArraySegment<Byte> buffer, BufferManager bufferManager, String contentType)
        {
            Message msg = Message.CreateMessage(this.m_MessageVersion, null);
            msg.Properties.Encoder = this;

            Byte[] array = new Byte[buffer.Count];
            Array.Copy(buffer.Array, buffer.Offset, array, 0, buffer.Count);
            msg.Properties.Add(RestMessageProperty.Name, new RestMessageProperty(new MemoryStream(array)));

            return msg;
        }

        public override Message ReadMessage(Stream stream, Int32 maxSizeOfHeaders, String contentType)
        {
            Message msg = Message.CreateMessage(this.m_MessageVersion, null);
            msg.Properties.Encoder = this;

            MemoryStream buffer = new MemoryStream();
            stream.CopyTo(buffer);
            msg.Properties.Add(RestMessageProperty.Name, new RestMessageProperty(buffer));

            return msg;
        }

        public override ArraySegment<Byte> WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
        {
            RestMessageProperty restMessage = (RestMessageProperty)message.Properties[RestMessageProperty.Name];
            MemoryStream buffer = restMessage.MessageData;

            Byte[] array = bufferManager.TakeBuffer((Int32)buffer.Length);
            buffer.GetBuffer().CopyTo(array, 0);
            return new ArraySegment<Byte>(array, 0, (Int32)buffer.Length);
        }

        public override void WriteMessage(Message message, Stream stream)
        {
            RestMessageProperty restMessage = (RestMessageProperty)message.Properties[RestMessageProperty.Name];

            restMessage.MessageData.CopyTo(stream);
        }
    }
}
